/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lbim.client.model;

import javax.microedition.location.Coordinates;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import lbim.client.main.MapUpdateListener;

/**
 *
 * @author Jestan
 */
public class LocationManager implements Runnable, LocationListener {
    private LocationProvider provider;
    private Criteria criteria;
    public Location currentLocation;
    private MapUpdateListener mapUpdateListener;

    public LocationManager() throws LocationException {
        initLocationProvider();
    }

    private void initLocationProvider() throws LocationException {
        criteria = new Criteria();
        criteria.setHorizontalAccuracy(500);
        criteria.setHorizontalAccuracy(500);
        criteria.setCostAllowed(true);
        provider = LocationProvider.getInstance(criteria);

        if (provider != null) {
            System.out.println("[LocationManager] LBS Provider OK");
        } else {
            System.out.println("[LocationManager] Failed to initialize the LBS Provider");
            throw new LocationException("Failed to initialize the LBS Provider");
        }

        Thread t = new Thread(this);
        t.start();
    }

    public MapUpdateListener getMapUpdateListener() {
        return mapUpdateListener;
    }

    public void setMapUpdateListener(MapUpdateListener mapUpdateListener) {
        this.mapUpdateListener = mapUpdateListener;
    }

    public LocXy getCurrentLocation() {
        Coordinates cor = currentLocation.getQualifiedCoordinates();
        return new LocXy(cor.getLongitude(), cor.getLatitude());
    }

    public void run() {
        try {
            provider.setLocationListener(this, 30, 10, 20);
            currentLocation = provider.getLocation(-1); // using default timeout
        } catch (LocationException ex) {
            System.out.println("[LocationManager] exception occured while getting the initial loc:"+ex);
        } catch (InterruptedException ex) {
            System.out.println("[LocationManager] exception occured while getting the initial loc:"+ex);
        }
    }

    public void locationUpdated(LocationProvider locationProvider, Location location) {
        this.currentLocation = location;
        if(mapUpdateListener != null)
        this.mapUpdateListener.locationUpdated();
    }

    public void providerStateChanged(LocationProvider locationProvider, int state) {
        if(mapUpdateListener != null)
        this.mapUpdateListener.deviceStateChanged(state);
    }


}
